import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../bank/Login.vue'
import Balance from '../bank/Balance.vue'
import Transfer from '../bank/Transfer.vue'
import Transactions from '../bank/Transactions.vue'
import ChangePassword from '../bank/ChangePassword.vue'
import Dashboard from '../bank/Dashboard.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
  },
  {
    path: '/balance',
    name: 'Balance',
    component: Balance,
  },
  {
    path: '/transfer',
    name: 'Transfer',
    component: Transfer,
  },
  {
    path: '/transactions',
    name: 'Transactions',
    component: Transactions,
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
  },
  {
    path: '/change-password',
    name: 'ChangePassword',
    component: ChangePassword,
  }
]

const router = new VueRouter({
  routes
})

// 添加导航守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果要访问的不是登录页，且没有token，则重定向到登录页
  if (to.path !== '/login' && !token) {
    next('/login')
  }
  // 如果已经有token，且要访问登录页，则重定向到首页
  else if (to.path === '/login' && token) {
    next('/dashboard')
  }
  else {
    next()
  }
})

export default router